from dataclasses import is_dataclass, asdict

from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass


class Base(MappedAsDataclass, DeclarativeBase):

    def to_dict(self):
        # 通过 __dict__
        # model_dict = dict(self.__dict__)
        # del model_dict["_sa_instance_state"]
        # return model_dict
        if is_dataclass(self.__class__):  # 判断是否为dataclass
            return asdict(self)
        return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}

        # 通过 __table__
        # return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}
